package com.atguigu.tingshu.album.mp;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class TrackReceiver {

    @Autowired
    private TrackInfoService trackInfoService ;

    @Autowired
    private RedisTemplate redisTemplate;

    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void trackStatUpdateTopic(ConsumerRecord<String, String> record){

        String value = record.value();
        if(!StringUtils.isEmpty(value)){

            //不等于空 要完成专辑播放量的更改
            TrackStatMqVo trackStatMqVo = JSON.parseObject(value, TrackStatMqVo.class);

            String businessNo = trackStatMqVo.getBusinessNo();
            String redisKey = "track:stat:" + businessNo ;

            // setIfAbsent方法底层调用的是redis的setnx命令，setnx表示如果key不存在，那么此时设置数据；如果key存在数据设置失败
            Boolean setIfAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, businessNo, 1, TimeUnit.HOURS);
            if(setIfAbsent) {
                // 调用service中的方法完成播放量的统计信息修改
                trackInfoService.trackStatUpdate(trackStatMqVo) ;
            }


        }

    }
}
